<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 消息提示 -->
      <el-alert title="添加商品信息" type="info" center show-icon></el-alert>

      <!-- 添加商品步骤显示器 -->
      <el-steps :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成 "></el-step>
      </el-steps>

      <el-form
        label-position="top"
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <!-- 左侧Tab栏 -->
        <!-- tab-position指示 tabs展示的位置 -->
        <el-tabs
          @tab-click="tabChange"
          :before-leave="leaveHandle"
          v-model="activeIndex"
          tab-position="left"
        >
          <el-tab-pane name="0" label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cateProps"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="1" label="商品参数">
            <el-form-item :label="item.attr_name" v-for="(item,index) in manyData" :key="index">
              <el-checkbox-group v-model="item.attr_vals" size="small">
                <el-checkbox :label="cb" border v-for="(cb,i) in item.attr_vals" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="2" label="商品属性">
            <el-form-item :label="item.attr_name" v-for="(item,index) in onlyData" :key="index">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="3" label="商品图片">
            <el-upload
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              list-type="picture"
              :headers="headers"
              multiple
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane name="4" label="商品内容">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <!-- 添加商品的按钮 -->
            <el-button @click="addGoods" type="primary" class="btnApp">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览弹框 -->
    <el-dialog title="图片预览" :visible.sync="previewDialog" width="50%">
      <img :src="previewImg" class="previewImg" />
    </el-dialog>
  </div>
</template>

<script>
// 导入lodash组件,来实现深拷贝
import _ from 'lodash'
export default {
  name: 'addGood',
  data() {
    return {
      // 默认激活的提示信息
      activeIndex: 0,

      // 添加商品表单数据
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 下拉框选中商品分类的id数组
        goods_cat: [],
        // 图片路径数组
        pics: [],
        // 商品的详情描述   富文本
        goods_introduce: '',
        attrs: []
      },
      // 添加商品验证规则
      addFormRules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请输入商品分类', trigger: 'blur' }]
      },

      // 商品分类数据
      cateList: [],
      // 商品分类下拉框的配置选项
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },

      // 商品动态参数数据
      manyData: [],
      // 商品静态属性数据
      onlyData: [],

      // 图片上传地址
      uploadUrl: 'http://118.190.160.53:8089/api/private/v1/upload',
      // 配置请求头 虽然全局配置的请求头,但upload内部封装了一套发送请求,所以要配置请求头
      headers: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 预览图片地址
      previewImg: '',
      // 控制预览图片弹框的显示隐藏
      previewDialog: false
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
    },

    // 监听下拉框的改变
    handleChange() {
      // console.log(this.addForm.good_cat)
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat.length = []
        return false
      }
    },

    // 监听tabs有没有切换 切换之前触发的方法
    leaveHandle(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类')
        return false
      }
    },

    // 监听tabs点击时触发的方法,获取商品参数数据
    async tabChange() {
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'many' } })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        })
        this.manyData = res.data
        // console.log(this.manyData)
      }
      if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'only' } })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.onlyData = res.data
        // console.log(this.onlyData)
      }
    },
    // 处理图片预览的方法
    handlePreview(file) {
      // console.log(file)
      this.previewImg = file.response.data.url
      // console.log(this.previewImg)
      this.previewDialog = true
    },
    // 处理删除图片的方法
    handleRemove(file) {
      // file是指要删除的图片的信息
      const removeImg = file.response.data.tmp_path
      const i = this.addForm.pics.findIndex(item => {
        return item.tmp_path === removeImg
      })
      this.addForm.pics.splice(i, 1)
    },
    // 处理上传图片成功的方法
    handleSuccess(response) {
      // response 是上传成功返回的信息
      const picInfo = { pic: response.data.tmp_path }
      this.addForm.pics.push(picInfo)
      // console.log(this.addForm.pics)
    },
    // 添加商品功能
    addGoods() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写必要的表单项')
        // 下拉框v-model绑定的必须是一个数组,但是提交的参数是个字符串
        // 在原数据上修改重新赋值的话,good_cat就变成了字符串,会报错
        // 解决方法一 用深拷贝来拷贝一个新的addForm数组,在新数组上修改赋值
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        // console.log(form)
        // 解决方法二 也可以使用展开运算符,返回的是一个新的数组
        // const newAddform = { ...this.addForm }
        // newAddform.goods_cat = newAddform.goods_cat.join(',')
        // console.log(newAddform)

        // 动态参数
        this.manyData.forEach(item => {
          const newParams = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addForm.attrs.push(newParams)
        })
        // 静态属性
        this.onlyData.forEach(item => {
          const newParams = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addForm.attrs.push(newParams)
        })
        form.attrs = this.addForm.attrs
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$router.push('/goods')
        // console.log(form)
      })
    }
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  }
}
</script>

<style lang="less" scoped>
.previewImg {
  width: 100%;
}
/deep/ .ql-editor {
  min-height: 300px;
}
.btnApp {
  margin-top: 15px;
}
</style>
